package com.kkb.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

@Controller
@RequestMapping("file")
public class FileController {
    @RequestMapping("hello")
    public String hello(){
        return "fileHandle";
    }
    @RequestMapping("upload")
    public String upload(@RequestParam("myFile") MultipartFile myFile, HttpServletRequest request)throws java.io.IOException, java.lang.IllegalStateException{
//源文件的名字改为32位不重复的字符串
//     1 获得源文件的名字
        String originalFilename = myFile.getOriginalFilename();
        System.out.println(originalFilename);
//     2 生成32位不重复字符串作为图片新名字，后缀要跟之前保存一致
        String fileName = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
//     3 存储图片所在的目录（文件夹）
        String realPath = request.getServletContext().getRealPath("/uploadFiles")+"/";
//     4 实现上传操作
        myFile.transferTo(new File(realPath+fileName));
        return "ok";
    }
}
